#! /usr/bin/python
# -*- coding: UTF-8 -*-

class menu(wx.Frame):
    def __init__(self, parent, menu_array):
        self.parent = parent
        self.CreateMenu(menu_array)
        
    def CreateMenu(self, menu_array):
        self.parent.SetMenuBar(self.BuildMenu(menu_array))

    def BuildSubmenu(self, subMenu):
        subMenuObject = wx.Menu()
        for item in subMenu:
            if not item: #allow now to add separators
                subMenuObject.AppendSeparator()
                continue
            statustext = ''; uihandler = None
            if len(item) == 3:
                id, title, action = item
            elif len(item) == 4:
                if type(item[2]) is str:
                    id, title, action, statustext = item
                else:
                    id, title, action, statustext = item
            elif len(item) == 5:
                id, title, action, statustext, uihandler = item
            else:
                raise AssertionError, \
                    'Item %s should have either 2 to 4 parts' % (item,)

            # Get id
            if type(id) == None:
                    _id = wx.NewId()
            else:
                _id = getattr(wx, id)
            if type(action) is list:
                # Recursive submenus
                subMenuObject.AppendMenu(_id, title, self.BuildSubmenu(action))
            else:
                button = subMenuObject.Append(_id, title, statustext)
                # Bind event
                if type(action) is str and action != '':
                    self.parent.Bind(wx.EVT_MENU, getattr(self.parent.events, action), button)

            if uihandler:
                wx.EVT_UPDATE_UI(self, _id, uihandler)

        return subMenuObject

    def BuildMenu(self, menu_array):
        mainMenu = wx.MenuBar()
        for title, subMenu in menu_array:
            mainMenu.Append(self.BuildSubmenu(subMenu), title)
        return mainMenu
